<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15-10-13
 * Time: 下午3:58
 */

class Posts_model extends CI_Model {


    private $conditions ;

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }


    /**
     * set query condition
     *
     * @param $conditions       条件数组
     * @param null $tb_name     表名
     * @param bool|FALSE $reset 设置查询条件之前是否重置
     * @return $this
     */
    public function set_query_condition($conditions,$tb_name = NULL, $reset = FALSE) {

        // default use post table
        $tb_name =  $tb_name  ?: \Beans\Post::$_TB_NAME ;
        // reset conditions
        $reset && $this->conditions = array();

        if ( count($conditions) )
        {
            foreach ( $conditions as $key => $val )
            {
                $key_ = $tb_name . '.' . $key;
                $val_ = $val;

                $this->conditions[$key_] = $val_;
            }
        }

        return $this;
    }

    /**
     * CI在每一次查询结束后回重置查询构造器，此处是将缓存的查询条件再次加入到查询构造器
     * 可以使用CI的查询缓存功能，但是会将缓存的条件同步到其他的Model中得查询构造器中
     */
    private function _set_query_condition() {
        if ( count($this->conditions) )
        {
            foreach ( $this->conditions as $key => $val )
            {
                $this->db->where($key,$val);
            }
        }
    }


    /**
     * get post count
     *
     * @return mixed
     */
    public function get_post_count() {
        $this->_set_query_condition();
        return $this->db->count_all_results( \Beans\Post::$_TB_NAME );
    }


    /**
     * Get post list
     *
     * @param $start
     * @param $rows
     * @return null
     * @throws
     */
    public function get_post_list($start = 0 ,$rows = 15) {

        $select_fields = \Beans\Post::$_TB_NAME . '.ID,' .
                         \Beans\Post::$_TB_NAME . '.post_title,' .
                         \Beans\Post::$_TB_NAME . '.post_date,' .
                         \Beans\User::$_TB_NAME . '.ID AS user_id,' .
                         \Beans\User::$_TB_NAME . '.user_nickname';

        // useful fields
        $this->db->select($select_fields);

        $this->db->from(\Beans\Post::$_TB_NAME);

        $this->db->join( \Beans\User::$_TB_NAME , \Beans\User::$_TB_NAME . '.ID = ' .
                                                  \Beans\Post::$_TB_NAME . '.post_author' , 'left' );

        $this->db->order_by(\Beans\Post::$_TB_NAME . '.post_date','DESC');
        $this->db->limit($start,$rows);

        $this->_set_query_condition();
        $query = $this->db->get();

        if ( !$query->num_rows() )
        {
           return NULL;
        }

        $result = $query->result();

        $this->load->model('categorys_model','categorys');
        $this->load->model('tags_model','tags');
        $this->load->model('relationships_model','relationships');

        // 采用category初始化relationships
        $this->relationships->initialize('category');

        // get category info
        foreach ( $result as $k => $row ) {
            $category_ids = $this->relationships->get_relation_ids($row->ID);
            $result[$k]->categorys = $this->categorys->get_category_arr_by_ids($category_ids);
        }

        // 采用tag初始化relationships
        $this->relationships->initialize('tag');
        // get tag info
        foreach ( $result as $k => $row )
        {
            $tag_ids = $this->relationships->get_relation_ids($row->ID);
            $result[$k]->tags = $this->tags->get_tag_arr_by_ids($tag_ids);
        }

        return $result;
    }


    /**
     * 获取单个文章
     *
     * @param $ID
     * @return null
     */
    public function get_post($ID) {

        $select_fields = \Beans\Post::$_TB_NAME . '.*,' .
                         \Beans\User::$_TB_NAME . '.ID AS user_id,' .
                         \Beans\User::$_TB_NAME . '.user_nickname';

        // useful fields
        $this->db->select($select_fields);

        $this->db->from(\Beans\Post::$_TB_NAME);

        $this->db->join( \Beans\User::$_TB_NAME ,
                         \Beans\User::$_TB_NAME . '.ID = ' .
                         \Beans\Post::$_TB_NAME . '.post_author' , 'left' );

        $this->db->where(\Beans\Post::$_TB_NAME . '.ID = ' . $ID);
        $query = $this->db->get();

        // 返回单独一行结果
        $post = $query->row();
        if ( !isset($post) )
        {
            return NULL;
        }

        $this->load->model('categorys_model','categorys');
        $this->load->model('tags_model','tags');
        $this->load->model('relationships_model','relationships');

        $this->relationships->initialize('category');
        $post->category_ids = $this->relationships->get_relation_ids($post->ID);

        $this->relationships->initialize('tag');
        $post->tag_ids = $this->relationships->get_relation_ids($post->ID);

        return $post;
    }

    /**
     * insert post
     *
     * @param \Beans\Post $post
     * @return bool | \Beans\Post $post
     */
    public function insert_post(\Beans\Post $post) {

        if ( !$post ) return FALSE;

        if ( FALSE === $this->db->insert(\Beans\Post::$_TB_NAME,$post) )
        {
            return FALSE;
        }

        $post->ID = $this->db->insert_id();
        //$sql = $this->db->set($post)->get_compiled_insert(\Beans\Post::$_TB_NAME);
        return $post;
    }


    /**
     * update post
     *
     * @param \Beans\Post $post
     * @return \Beans\Post|bool
     */
    public function update_post( \Beans\Post $post ) {

        if ( !$post ) return FALSE;
        if ( FALSE === $this->db->update( \Beans\Post::$_TB_NAME,$post,'ID = '.$post->ID ) )
        {
            return FALSE;
        }

        return $post;
    }


    /**
     * delete post
     *
     * @param $ids_string
     * @param string $delimiter
     * @return mixed
     * @throws Exception
     */
    public function delete_post($ids_string,$delimiter = ',') {

        $ids_array  = explode($delimiter,strval($ids_string));

        if (empty($ids_array))
        {
            throw new Exception('请传入要删除的分类的ID');
        }

        foreach ($ids_array as $key => $ID)
        {
            // if id to hashids_encode, hashids_decode it,
            // else do nothing
            $ids_array[$key] = hashids_decode($ID);
        }

        $this->db->where_in('ID',$ids_array);
        return $this->db->delete(\Beans\Post::$_TB_NAME);
    }


    public function trans_start() {
        $this->db->trans_begin();
        return $this;
    }

    public function trans_rollback() {
        $this->db->trans_rollback();
        return $this;
    }

    public function trans_commit() {
        $this->db->trans_commit();
        return $this;
    }

    public function trans_off() {
        $this->db->trans_off();
        return $this;
    }

}